package com.yichi;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.yichi.biz_bean.DeviceOperInfo;
import com.yichi.biz_bean.DeviceOperType;
import com.yichi.device_bean.BatteryStore;
import com.yichi.device_bean.BmsParam;
import com.yichi.device_bean.BmsStatus;
import com.yichi.device_bean.DeviceInfo;
import com.yichi.device_bean.PcbDataInfo;
import com.yichi.device_bean.PcbStatusInfo;
import com.yichi.device_bean.PlcInfo;
import com.yichi.global.AppConfig;
import com.yichi.global.EventDef;
import com.yichi.global.PlatformResult;
import com.yichi.manager.OnHttpResponseListener;
import com.yichi.service.DeviceService;
import com.yichi.service.IccardService;
import com.yichi.service.MqttService;
import com.yichi.service.PcbService;
import com.yichi.service.PlatformService;
import com.yichi.service.PlcService;
import com.yichi.util.BeanUtil;
import com.yichi.util.DialogUtil;
import com.yichi.util.JsonUtil;
import com.yichi.util.MapUtil;
import com.yichi.util.StringUtil;
import com.yichi.util.ToastUtil;
import com.yichi.util.Utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "MainActivity";

    private ImageView iv_logo;
    private TextView tv_time_curr;
    private TextView tv_device_no, tv_contact, tv_device_name;
    private TextView tv_bot_kq, tv_bot_kc, tv_bot_cdz, tv_bot_wd, tv_bot_gl, tv_title_tip;
    private View adContainer, rightContainer, statusContainer;
    private FragmentManager manager;
    private Map mqttMap;
    //弹出管理密码
    int count = 3;
    long time = 1000;
    long[] mHits = new long[count];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        findView();
        setView();

        loadDeviceInfo();
        //注册自定义事件
        this.registerEvent();
        //启动定时任务
        startTimeTask();
//        DeviceService.inst.startSubmitPlatformOutputStoreInfoTask();
//        PcbService.inst.startQueryPcbTask();//启动任务
//        DeviceService.inst.startCheckDispachBatteryTask();
//        DeviceService.inst.startHandleDispachBatteryTask();

        manager = getSupportFragmentManager();
        //左
        Fragment adFragment = new AdFragment();
        Fragment operateFragment = new OperateFragment();
        //右
        Fragment loginFragment = new LoginFragment();
        Fragment quDianTipFragment = new QuDianTipFragment();
        Fragment quDianTipFragment1 = new QuDianTipFragment("用户张**的订单进行中", "仓门已开，请取电，取出后请关闭仓门");
        Fragment adminOperateFragment = new AdminOperateFragment(null);
        Fragment quDianXinXiFragment = new QuDianXinXiFragment();
        Fragment quDianConfirmFragment = new QuDianConfirmFragment();
        Fragment quDianSelectFragment = new QuDianSelectFragment("游客");
        Fragment cunDianSelectFragment = new CunDianSelectFragment();
        Fragment cunDianOpenDoorFragment = new CunDianOpenDoorFragment();
        Fragment cunDianPutInFragment = new CunDianPutInFragment();
        Fragment cunDianCloseDoorFragment = new CunDianCloseDoorFragment();
        Fragment enterPasswordFragment = new EnterPasswordFragment("", "");
        Fragment plcTestFragment = new AdminPlcTestFragment();
        manager.beginTransaction().replace(R.id.ad_fragment_container, adFragment).commit();
        manager.beginTransaction().replace(R.id.login_fragment_container, loginFragment).commit();

//展示全屏操作维护人员操作Fragment
//        statusContainer.setVisibility(View.GONE);
//        adContainer.setVisibility(View.GONE);
//        rightContainer.setVisibility(View.GONE);
//        manager.beginTransaction().replace(R.id.admin_fragment_container, plcTestFragment).commit();//测试页面
//        manager.beginTransaction().replace(R.id.admin_fragment_container, adminOperateFragment).commit();//运维页面
    }

    private void setView() {
        //弹出设置密码框
        iv_logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //每次点击时，数组向前移动一位
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                //为数组最后一位赋值
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] >= (SystemClock.uptimeMillis() - time)) {
                    //数组重新初始化
                    mHits = new long[count];
                    DialogUtil.showSpaceEditDialog(MainActivity.this,
                            "输入密码",
                            "请输入管理密码",
                            "管理密码错误",
                            false, new DialogUtil.MyCustomDialogListener() {
                                @Override
                                public void ok() {
//                                    showSettingDialog();
                                    startActivity(new Intent(MainActivity.this, SettingActivity.class));
                                }

                                @Override
                                public void no() {
                                }
                            });
                }
            }
        });
    }

    private void loadDeviceInfo() {
        tv_device_no.setText(AppConfig.DEVICE_ID);
        if (DeviceService.inst.deviceInfo != null) {
            renderDeviceInfo(DeviceService.inst.deviceInfo);
        } else {
            getDeviceInfo();
        }
    }

    private void getDeviceInfo() {
        try {
            PlatformService.getCabinetInfoByNum(new OnHttpResponseListener() {
                @Override
                public void success(Call call, Response response) throws IOException {
                    String s = response.body().string();
                    Map<String, Object> map;
                    try {
                        map = JsonUtil.parseMap(s);
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage(), e);
                        return;
                    }
                    Integer code = MapUtil.getInteger(map, "code");
                    String msg = MapUtil.getString(map, "msg");
                    if (!code.equals(200)) {
                        return;
                    }
                    Map dataMap = MapUtil.getMap(map, "data");
                    if (dataMap == null) {
                        return;
                    }
                    String cabinetName = MapUtil.getString(dataMap, "cabinetName");
                    String contactNumber = MapUtil.getString(dataMap, "contactNumber");
                    DeviceInfo deviceInfo = new DeviceInfo();
                    deviceInfo.setDeviceName(cabinetName);
                    deviceInfo.setContact(contactNumber);
                    DeviceService.inst.deviceInfo = deviceInfo;
                    runOnUiThread(() -> {
                        renderDeviceInfo(deviceInfo);
                    });
                }

                @Override
                public void failed(Call call, IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private void renderDeviceInfo(DeviceInfo deviceInfo) {
        tv_contact.setText(deviceInfo.getContact());
        tv_device_name.setText(deviceInfo.getDeviceName());
    }

    private void startTimeTask() {
        ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();
        schedule.scheduleWithFixedDelay(() -> {
            runOnUiThread(() -> {
                String currTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                tv_time_curr.setText(currTime);
            });
        }, 0, 1, TimeUnit.SECONDS);//初始延迟0秒，之后每隔1秒执行一次
    }

    private void findView() {
        iv_logo = findViewById(R.id.iv_logo);
        tv_time_curr = findViewById(R.id.tv_time_curr);
        tv_title_tip = findViewById(R.id.tip);

        tv_bot_kq = findViewById(R.id.tv_bot_kq);
        tv_bot_kc = findViewById(R.id.tv_bot_kc);
        tv_bot_cdz = findViewById(R.id.tv_bot_cdz);
        tv_bot_wd = findViewById(R.id.tv_bot_wd);
        tv_bot_gl = findViewById(R.id.tv_bot_gl);

        statusContainer = findViewById(R.id.status_container);
        adContainer = findViewById(R.id.ad_fragment_container);
        rightContainer = findViewById(R.id.right_container);

        tv_device_no = findViewById(R.id.tv_device_no);
        tv_contact = findViewById(R.id.tv_contact);
        tv_device_name = findViewById(R.id.tv_device_name);
    }

    public void setTitleTip(String s) {
        tv_title_tip.setText(s);
    }

    public void goHome() {
        statusContainer.setVisibility(View.VISIBLE);
        adContainer.setVisibility(View.VISIBLE);
        rightContainer.setVisibility(View.VISIBLE);

        Fragment admin_fragment_container = manager.findFragmentById(R.id.admin_fragment_container);
        if (admin_fragment_container != null) {
            manager.beginTransaction().remove(admin_fragment_container).commit();
        }

        Fragment adFragment = new AdFragment();
        Fragment loginFragment = new LoginFragment();
        manager.beginTransaction().replace(R.id.ad_fragment_container, adFragment).commit();
        manager.beginTransaction().replace(R.id.login_fragment_container, loginFragment).commit();

        DeviceService.inst.setDeviceOperInfo(null);
    }

    public void goFaceSelectOps(String realName) {
        statusContainer.setVisibility(View.VISIBLE);
        adContainer.setVisibility(View.VISIBLE);
        rightContainer.setVisibility(View.VISIBLE);

        Fragment admin_fragment_container = manager.findFragmentById(R.id.admin_fragment_container);
        if (admin_fragment_container != null) {
            manager.beginTransaction().remove(admin_fragment_container).commit();
        }

        Fragment operateFragment = new OperateFragment();
        Fragment quDianSelectFragment = new QuDianSelectFragment(realName);
        manager.beginTransaction().replace(R.id.ad_fragment_container, operateFragment).commit();
        manager.beginTransaction().replace(R.id.login_fragment_container, quDianSelectFragment).commit();
    }

    private void goOps(Map<String, Object> orderMap) {
        statusContainer.setVisibility(View.GONE);
        adContainer.setVisibility(View.GONE);
        rightContainer.setVisibility(View.GONE);

        AdminOperateFragment adminOperateFragment = new AdminOperateFragment(orderMap);
        manager.beginTransaction().replace(R.id.admin_fragment_container, adminOperateFragment).commit();
    }

    /**
     * 注册事件
     */
    private void registerEvent() {
        //小程序取电事件
        LiveEventBus
                .get(EventDef.EVENT_WECHAT_TAKE_REQ, Map.class)
                .observe(this, new Observer<Map>() {
                    @Override
                    public void onChanged(Map map) {
                        Executors.newSingleThreadExecutor().execute(() -> {
                            handleWechatTakeReq(map);
                        });
                    }
                });
        //小程序存电事件
        LiveEventBus
                .get(EventDef.EVENT_WECHAT_RETURN_REQ, Map.class)
                .observe(this, new Observer<Map>() {
                    @Override
                    public void onChanged(Map map) {
                        handleWechatReturnReq(map);
                    }
                });
        //小程序运维事件
        LiveEventBus
                .get(EventDef.EVENT_WECHAT_OPSDEV_REQ, Map.class)
                .observe(this, new Observer<Map>() {
                    @Override
                    public void onChanged(Map map) {
                        mqttMap = map;
                        handleOpsDev(map);
                    }
                });
        //运维人员密码输入正确事件
        LiveEventBus
                .get(EventDef.EVENT_OPSUSER_PWD_VERRIFY_PASSED, String.class)
                .observe(this, new Observer<String>() {
                    @Override
                    public void onChanged(String s) {
                        handlePwdVerifyPassed(mqttMap);
                    }
                });
        //pcb数据信息
        LiveEventBus
                .get(EventDef.EVENT_PCB_DATA_QUERY_TASK, PcbDataInfo.class)
                .observe(this, new Observer<PcbDataInfo>() {
                    @Override
                    public void onChanged(PcbDataInfo pcbDataInfo) {
                        //更新UI
                        runOnUiThread(() -> {
                            tv_bot_wd.setText(pcbDataInfo.getDeviceHJWD().toString());
                            tv_bot_gl.setText(pcbDataInfo.getDeviceYGGL().toString());
                        });
                        //更新充电仓电池数据
                        Map<Integer, BmsParam> bmsParamMap = pcbDataInfo.getBmsParamMap();
                        for (Integer storeNo : bmsParamMap.keySet()) {
                            BmsParam bmsParam = bmsParamMap.get(storeNo);
                            BatteryStore batteryStore = DeviceService.inst.getBatteryStoreByStoreNo(storeNo);
                            if (batteryStore.getBmsParam() == null) {
                                batteryStore.setBmsParam(bmsParam);
                            } else {
                                BeanUtil.copyBmsParam(bmsParam, batteryStore.getBmsParam());
                            }
                            batteryStore.setBatterySoc(bmsParam.getSoc());
                            float lc = Utils.getMileage(bmsParam.getSoc(), bmsParam.getSoh());
                            batteryStore.setBatteryMileage(lc);
                        }
                    }
                });
        //pcb状态数据
        LiveEventBus.get(EventDef.EVENT_PCB_STATUS_QUERY_TASK, PcbStatusInfo.class)
                .observe(this, new Observer<PcbStatusInfo>() {
                    @Override
                    public void onChanged(PcbStatusInfo pcbStatusInfo) {
                        Map<String, BmsStatus> bmsStatusMap = pcbStatusInfo.getBmsStatusMap();
                        for (String key : bmsStatusMap.keySet()) {
                            BmsStatus bmsStatus = bmsStatusMap.get(key);
                            BatteryStore batteryStore = DeviceService.inst.getBatteryStoreByStoreNo(Integer.valueOf(key));
                            if (batteryStore.getBmsStatus() == null) {
                                batteryStore.setBmsStatus(bmsStatus);
                            } else {
                                BeanUtil.copyBmsStatus(bmsStatus, batteryStore.getBmsStatus());
                            }
                        }
                    }
                });
        //电池仓统计
        LiveEventBus
                .get(EventDef.EVENT_STORE_TOTAL_TASK, Map.class)
                .observe(this, new Observer<Map>() {
                    @Override
                    public void onChanged(Map map) {
                        runOnUiThread(() -> {
                            tv_bot_kc.setText(MapUtil.getString(map, "kc"));
                            tv_bot_kq.setText(MapUtil.getString(map, "kq"));
                            tv_bot_cdz.setText(MapUtil.getString(map, "cdz"));
                        });
                    }
                });
    }

    /**
     * 处理小程序取电请求
     * 柜门编号，低中高，456
     * {
     * "request": "take"，   //  取电
     * "cabinetID": 4，       //  4~6对应取柜“低”、“中”和“高”
     * "userName": "张三"，//  用户姓名
     * "orderId": 4,1         //  逗号分割，   逗号前面是订单Id     后面  1代表  取   2 表示 还
     * }
     */
    private void handleWechatTakeReq(Map<String, Object> map) {
        Integer cabinetID = MapUtil.getInteger(map, "cabinetID");
        String orderId = MapUtil.getString(map, "orderId");
        String userName = MapUtil.getString(map, "userName");
        String maskName = Utils.maskString(userName);

        //1 验证
        if (DeviceService.inst.getDeviceOperInfo() != null) {
            //当前操作未结束
            PlatformResult result = new PlatformResult(500, "take_battery", "取电失败：设备运行中，请稍后...");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "取电失败：设备运行中，请稍后...");
            });
            return;
        }

        //2 锁住。其它人不能操作
        DeviceOperInfo deviceOperInfo = new DeviceOperInfo();
        DeviceService.inst.setDeviceOperInfo(deviceOperInfo);
        deviceOperInfo.setOperType(DeviceOperType.USER_BATTERY_TAKE);
        deviceOperInfo.setUserName(userName);
        deviceOperInfo.setOrderId(orderId);

        //3 是否有电池
        BatteryStore outputStore = DeviceService.inst.getBatteryStoreByStoreNo(cabinetID);
//        outputStore.setHasBattery(true);//测试代码
//        outputStore.setBatteryNo("DC0001");//测试代码
        if (!outputStore.getHasBattery() || StringUtil.isEmpty(outputStore.getBatteryNo())) {
            PlatformResult result = new PlatformResult(500, "take_battery", "取电失败：取电仓没有电池");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());
            DeviceService.inst.setDeviceOperInfo(null);//释放

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "取电失败：取电仓没有电池");
            });
            return;
        }

        //4 打开仓门，界面跳转
        PlcService.inst.handleOpenDoor(cabinetID);
        Log.i(TAG, "发送打开仓门命令");

        //5 门是否打开
        boolean openDoor = PlcService.inst.isOpenDoor(cabinetID);
        if (!openDoor) {
            PlatformResult result = new PlatformResult(500, "take_battery", "取电失败：仓门打开失败");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());
            DeviceService.inst.setDeviceOperInfo(null);//释放

            runOnUiThread(() -> {
                ToastUtil.show(this, "取电失败：仓门打开失败");
            });
            return;
        }
        outputStore.setDoorOpen(true);
        DeviceService.inst.saveData();
        Log.i(TAG, "门已打开");

        //6 跳出提示页面：“仓门开了”
        runOnUiThread(() -> {
            Fragment adFragment = new AdFragment();
            Fragment quDianTipFragment = new QuDianTipFragment(String.format("用户%s正在取电", maskName), "仓门已开，请取电，取出后\n请关闭仓门");
            manager.beginTransaction().replace(R.id.ad_fragment_container, adFragment).commit();
            manager.beginTransaction().replace(R.id.login_fragment_container, quDianTipFragment).commit();
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage(), e);
        }

        //7 mqtt提交。操作成功：电池信息
        PlatformResult result = new PlatformResult(200, "take_battery", "仓门打开成功");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderId", map.get("orderId"));
        dataMap.put("cabinetID", map.get("cabinetID"));
        dataMap.put("batteryNum", outputStore.getBatteryNo());
        BmsParam bmsParam = outputStore.getBmsParam();
        if (bmsParam != null) {
            dataMap.put("batteryState", "");
            dataMap.put("batteryCapacity", bmsParam.getSoc());
            dataMap.put("batteryVoltage", bmsParam.getTotalVoltage());
            dataMap.put("batteryMileage", outputStore.getBatteryMileage());
        } else {
            dataMap.put("batteryState", "");
            dataMap.put("batteryCapacity", 80);
            dataMap.put("batteryVoltage", 55);
            dataMap.put("batteryMileage", 45);
        }
        result.setData(dataMap);
        MqttService.inst.sendMsg(result.toJsonString());
        Log.i(TAG, "提交平台成功");

        //8 是否关闭仓门
        PlcInfo closeDoor = PlcService.inst.isCloseDoor(cabinetID);
        outputStore.setDoorOpen(false);
        DeviceService.inst.saveData();
        Integer batteryStatus = closeDoor.getBatteryStatusByStoreNo(cabinetID);
        if (batteryStatus.equals(0)) {
            //电池取走了
            BeanUtil.setBatteryStoreEmpty(outputStore);
            //保存数据
            DeviceService.inst.saveData();
            PlatformService.updateIsTakeBattery(orderId);//http提交，已取走电池
        }
        PlatformService.updateTakeCloseDoor(orderId);//httpt提交，已关门
        Log.i(TAG, "提交平台关门");

        //9 回首页
        runOnUiThread(() -> {
            goHome();
        });
        Log.i(TAG, "取电完成");
    }

    /**
     * 处理小程序存电请求
     * 柜门编号，低中高，123
     * {
     * "request": "return"， // 还电
     * "cabinetID": 4， // 柜门编号（1~3，分别对应“低”“中”“高”存入柜）
     * "userName": "张三"，// 用户姓名
     * "orderId": 4,1 // 逗号分割， 逗号前面是订单Id 后面 1代表 取 2 表示 还
     * }
     */
    private void handleWechatReturnReq(Map<String, Object> map) {
        Integer cabinetID = MapUtil.getInteger(map, "cabinetID");
        String orderId = MapUtil.getString(map, "orderId");
        String userName = MapUtil.getString(map, "userName");
        String maskName = Utils.maskString(userName);

        //1 验证
        if (DeviceService.inst.getDeviceOperInfo() != null) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：设备运行中，请稍后...");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "还电失败：设备运行中，请稍后...");
            });
            return;
        }

        //2 锁住
        DeviceOperInfo deviceOperInfo = new DeviceOperInfo();
        DeviceService.inst.setDeviceOperInfo(deviceOperInfo);
        deviceOperInfo.setOperType(DeviceOperType.USER_BATTERY_RETURN);
        deviceOperInfo.setUserName(userName);
        deviceOperInfo.setOrderId(orderId);
        Log.i(TAG, "开始存电");

        //3 是否有空仓位
        BatteryStore inputStore = DeviceService.inst.getBatteryStoreByStoreNo(cabinetID);
        if (inputStore == null || inputStore.getHasBattery() || !inputStore.getLockStatus().equals(0)) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：没空余的仓位了");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());
            DeviceService.inst.setDeviceOperInfo(null);

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "还电失败：没空余的仓位了");
            });
            return;
        }

        //4 开仓门
        PlcService.inst.handleOpenDoor(cabinetID);
        Log.i(TAG, "发送开门指令");

        //5 跳出提示页面：正在开门
        runOnUiThread(() -> {
            Fragment adFragment = new AdFragment();
            Fragment quDianTipFragment = new QuDianTipFragment(String.format("用户%s正在还电", maskName), "正在开门请稍等\n请留意仓门");
            manager.beginTransaction().replace(R.id.ad_fragment_container, adFragment).commit();
            manager.beginTransaction().replace(R.id.login_fragment_container, quDianTipFragment).commit();
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage(), e);
        }

        //6 门是否打开
        boolean openDoor = PlcService.inst.isOpenDoor(cabinetID);
        if (!openDoor) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：仓门未打开");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "还电失败：仓门未打开");
                goHome();
            });
            return;
        }
        inputStore.setDoorOpen(true);
        DeviceService.inst.saveData();
        Log.i(TAG, "门已打开");

        //7 跳出提示页面：仓门开了
        runOnUiThread(() -> {
            Fragment adFragment = new AdFragment();
            Fragment quDianTipFragment = new QuDianTipFragment(String.format("用户%s正在存电", maskName), "仓门已开，请存电\n存入后请关闭仓门");
            manager.beginTransaction().replace(R.id.ad_fragment_container, adFragment).commit();
            manager.beginTransaction().replace(R.id.login_fragment_container, quDianTipFragment).commit();
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage(), e);
        }

        //7 仓门关了
        PlcInfo closeDoor = PlcService.inst.isCloseDoor(cabinetID);
        if (closeDoor == null) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：操作已中断");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "还电失败：操作已中断");
                goHome();
            });
            return;
        }
        inputStore.setDoorOpen(false);
        DeviceService.inst.saveData();
        Log.i(TAG, "门关了");

        //8 是否有电池
        String[] batteryNoArr = IccardService.inst.queryBatteryNo();
        if (batteryNoArr == null || batteryNoArr.length < 3) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：没放入电池");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            MqttService.inst.sendMsg(result.toJsonString());

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "还电失败：没放入电池");
                goHome();
            });
            return;
        }
        String batteryNo = batteryNoArr[cabinetID - 1];
        if (StringUtil.isEmpty(batteryNo)) {
            PlatformResult result = new PlatformResult(500, "return_battery", "还电失败：没放入电池");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", map.get("orderId"));
            dataMap.put("cabinetID", map.get("cabinetID"));
            result.setData(dataMap);
            MqttService.inst.sendMsg(result.toJsonString());

            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "还电失败：没放入电池");
                goHome();
            });
            return;
        }
        Log.i(TAG, "存入电池编号：" + batteryNo);
        inputStore.setHasBattery(true);
        inputStore.setBatteryNo(batteryNo);
        inputStore.setLockStatus(0);
        DeviceService.inst.saveData();

        //9 提交平台操作成功了
        PlatformResult result = new PlatformResult(200, "return_battery", "电池归还成功");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderId", map.get("orderId"));
        dataMap.put("cabinetID", map.get("cabinetID"));
        dataMap.put("batteryNum", batteryNo);
        result.setData(dataMap);
        MqttService.inst.sendMsg(result.toJsonString());
        Log.i(TAG, "提交平台完成");

        //10 回首页
        runOnUiThread(() -> {
            goHome();
        });
        Log.i(TAG, "还电完成");
    }

    /**
     * 维护人员运维额
     *
     * @param map {
     *            "request": "opsdev"， // 维护
     *            "opsUserId": ， // 维护人员ID
     *            "userName": 4， // 维护姓名
     *            "cabinetNum": "nzh001"，// 机柜编号
     *            "passWord": "1234"，// 密码 对比用户输入的 是否正确（前端对比）
     *            }
     */
    private void handleOpsDev(Map<String, Object> map) {
        Integer cabinetNum = MapUtil.getInteger(map, "cabinetNum");
        String opsUserId = MapUtil.getString(map, "opsUserId");
        String userName = MapUtil.getString(map, "userName");
        String maskName = Utils.maskString(userName);
        String passWord = MapUtil.getString(map, "passWord");

        //1 验证
        if (DeviceService.inst.getDeviceOperInfo() != null) {
            runOnUiThread(() -> {
                ToastUtil.show(MainActivity.this, "设备正在运行，请稍后...");
            });
            return;
        }

        //2 锁定
        DeviceOperInfo deviceOperInfo = new DeviceOperInfo();
        DeviceService.inst.setDeviceOperInfo(deviceOperInfo);
        deviceOperInfo.setOperType(DeviceOperType.USER_BATTERY_TAKE);
        deviceOperInfo.setUserName(userName);

        //3 输入密码
        runOnUiThread(() -> {
            Fragment adFragment = new AdFragment();
            Fragment enterPasswordFragment = new EnterPasswordFragment(userName, passWord);
            manager.beginTransaction().replace(R.id.ad_fragment_container, adFragment).commit();
            manager.beginTransaction().replace(R.id.login_fragment_container, enterPasswordFragment).commit();
        });
    }

    /**
     * 维护密码验证通过
     */
    private void handlePwdVerifyPassed(Map<String, Object> map) {
        //获取工单
        String cabinetNum = MapUtil.getString(map, "cabinetNum");
        Integer opsUserId = MapUtil.getInteger(map, "opsUserId");
        String passWord = MapUtil.getString(map, "passWord");

        PlatformService.getListByNumSync(cabinetNum, opsUserId, passWord, new OnHttpResponseListener() {

            @Override
            public void success(Call call, Response response) throws IOException {
                String s = response.body().string();
                Log.i(TAG, "收到工单：" + s);

                Map<String, Object> map = JsonUtil.parseMap(s);
                Integer code = MapUtil.getInteger(map, "code");
                String msg = MapUtil.getString(map, "msg");

                if (code != 200) {
                    runOnUiThread(() -> {
                        ToastUtil.show(MainActivity.this, String.format("工单获取失败：%s", msg));
                        goHome();
                    });
                    return;
                }

                List<Map<String, Object>> rows = (List<Map<String, Object>>) map.get("rows");
                if (rows.isEmpty()) {
                    runOnUiThread(() -> {
                        ToastUtil.show(MainActivity.this, "工单未找到");
                        goHome();
                    });
                    return;
                }

                Map<String, Object> orderMap = rows.get(0);
                runOnUiThread(() -> {
                    goOps(orderMap);
                });
            }

            @Override
            public void failed(Call call, IOException e) {
                Log.e(TAG, e.getMessage(), e);
                runOnUiThread(() -> {
                    ToastUtil.show(MainActivity.this, e.getMessage());
                    goHome();
                });
            }

        });
    }
}